package com.shaoshaohuo.app.wxapi;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.alipay.sdk.PayResult;
import com.alipay.sdk.SignUtils;
import com.alipay.sdk.app.PayTask;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.constant.UMengEventID;
import com.shaoshaohuo.app.entity.AccountDetailEntity;
import com.shaoshaohuo.app.entity.AccountDetailEntity.AccountDetail;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.CheckPayPwdEntity;
import com.shaoshaohuo.app.entity.PayResultEneity;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.ui.PayManageActivity;
import com.shaoshaohuo.app.ui.pay.PayResultActivity;
import com.shaoshaohuo.app.utils.StringHelper;
import com.shaoshaohuo.app.utils.ToastUtil;
import com.shaoshaohuo.app.view.PayDialog;
import com.shaoshaohuo.app.view.PayDialog.OnBtClickListener;
import com.shaoshaohuo.app.view.TopbarView;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class PayActivity extends BaseActivity implements OnClickListener,IWXAPIEventHandler {

	private TopbarView mTopbarView;

	private TextView mTotalPriceText;
	private View mZhifubaoLayout;
	private View mWeixinLayout;
	private View mYueLayout;
	
	private TextView mLeftAmountText;
	
	private String orderid;
	private String totalPrice;
	
	private String couponid = "";
	private String origincontact;
	private String originphone;
	private String bxprice;
	private String bxnum;

	protected PayResultEneity aliPayResult;
	protected PayResultEneity weixinResult;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pay);
		
		initData();
		initView();
		setUpView();
		getAccountDetail();
		initWx();
	}

	private void getAccountDetail() {
		startLoadingDialog();
		RequestService.getInstance().getAccountDetail(this, AccountDetailEntity.class, new RequestListener() {
			
			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if(resultData.isOk()){
					AccountDetailEntity entity = (AccountDetailEntity) resultData;
					updateUi(entity);
				}else{
					showToast(resultData.getMsg());
				}
			}
			
			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(R.string.please_check_network);
			}
		});
	}

	protected void updateUi(AccountDetailEntity entity) {
		AccountDetail data = entity.getData();
		mLeftAmountText.setText("账户余额(余额:"+data.getFreetotal()+")");
	}
	
	private void initData() {
		Intent intent = getIntent();
		orderid = intent.getStringExtra(ExtraName.orderid);
		totalPrice = intent.getStringExtra(ExtraName.totalPrice);
		couponid = intent.getStringExtra(ExtraName.couponid);
		origincontact = intent.getStringExtra(ExtraName.origincontact);
		originphone = intent.getStringExtra(ExtraName.originphone);
		bxprice = intent.getStringExtra(ExtraName.bxprice);
		bxnum = intent.getStringExtra(ExtraName.bxnum);
	}

	private void initView() {
		mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

		mTotalPriceText = (TextView) this.findViewById(R.id.textview_total_price);
		mZhifubaoLayout = this.findViewById(R.id.layout_zhifubao);
		mWeixinLayout = this.findViewById(R.id.layout_weixin);
		mYueLayout = this.findViewById(R.id.layout_yue);
		mLeftAmountText = (TextView) this.findViewById(R.id.textview_left_amount);
	}

	private void setUpView() {
		mTopbarView.setCenterText("支付");
		mTopbarView.setLeftView(true, true);

		mTotalPriceText.setText("支付金额:￥"+totalPrice);
		
		mZhifubaoLayout.setOnClickListener(this);
		mWeixinLayout.setOnClickListener(this);
		mYueLayout.setOnClickListener(this);
		
	}

	@Override
	public void onClick(View v) {
        MobclickAgent.onEvent(this, UMengEventID.CLICK_PAY);
		switch (v.getId()) {
		case R.id.layout_zhifubao:
//			Intent intent = new Intent(this,OrderDetailActivity.class);
//			startActivity(intent);
			payByAlipay();
			break;
		case R.id.layout_weixin:
//			Intent intent1 = new Intent(this,OrderDetailActivity.class);
//			startActivity(intent1);
			payByWeixin();
			break;
		case R.id.layout_yue:
		    checkPayPwd();
			break;
		}
	}
	
	private void showPwdDialog(CheckPayPwdEntity entity) {
        if("1".equals(entity.getData().getIsset())){
            PayDialog dialog = new PayDialog(this);
            dialog.setOnBtClickListener(new OnBtClickListener() {
                
                @Override
                public void onPayClick(String pwd) {
//                  showToast(pwd);
//                  Intent intent2 = new Intent(PayActivity.this,OrderDetailActivity.class);
//                  startActivity(intent2);
                    payOrderByBalance(pwd);
                }
            });
            dialog.show();
        }else{
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("未设置支付密码,请先设置支付密码");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(PayActivity.this,PayManageActivity.class);
                    startActivity(intent);
                }
            });
            builder.create().show();
        }
    }
    
    private void checkPayPwd(){
        startLoadingDialog();
        RequestService.getInstance().checkPayPwd(this, CheckPayPwdEntity.class, new RequestListener() {
            
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if(resultData.isOk()){
                    CheckPayPwdEntity entity = (CheckPayPwdEntity) resultData;
                    showPwdDialog(entity);
                }else{
                    showToast(resultData.getMsg());
                }
            }
            
            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }
        });
    }
	
	private void payByAlipay() {
		startLoadingDialog();
		RequestService.getInstance().payOrderByBalance(this, orderid, "alipay", "", "0", couponid, origincontact, originphone, bxprice, bxnum, PayResultEneity.class, new RequestListener() {
			
			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if(resultData.isOk()){
					aliPayResult = (PayResultEneity) resultData;
//					showToast("支付成功");
					aliPay();
				}else{
					showToast(resultData.getMsg());
				}
			}
			
			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(R.string.please_check_network);
			}
		});
	}
	
	private void payByWeixin() {
		startLoadingDialog();
		RequestService.getInstance().payOrderByBalance(this, orderid, "weixin", "", "0", couponid, origincontact, originphone, bxprice, bxnum, PayResultEneity.class, new RequestListener() {
			
			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if(resultData.isOk()){
					weixinResult = (PayResultEneity) resultData;
                    WXPayEntryActivity.setCurrentPayWay(WXPayEntryActivity.PAY_ORDER_SHIPPER);
                    WXPayEntryActivity.setCurrentPayEntity(weixinResult);
					genPayReq();
					sendPayReq();
				}else{
					showToast(resultData.getMsg());
				}
			}
			
			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(R.string.please_check_network);
			}
		});
	}

	private void payOrderByBalance(String passwd) {
		startLoadingDialog();
		RequestService.getInstance().payOrderByBalance(this, orderid, "", StringHelper.toMD5(passwd), totalPrice, couponid, origincontact, originphone, bxprice, bxnum, PayResultEneity.class, new RequestListener() {
			
			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if (resultData.isOk()) {
//					showToast("支付成功");
//					toOrderDetail();
					PayResultEneity re = (PayResultEneity) resultData;
					Intent successIntent = new Intent(PayActivity.this, PayResultActivity.class);
					successIntent.putExtra(PayResultActivity.FORWARD_KEY, PayResultActivity.FORWARD_CART_ORDER_LIST);
					successIntent.putExtra(PayResultActivity.KEY_RESULT, PayResultActivity.VALUE_SUCCESS);
					successIntent.putExtra(PayResultActivity.KEY_MONEY, re.getData().getMoney() + "元");
					successIntent.putExtra(PayResultActivity.KEY_PAY_WAY, "账户余额");
					successIntent.putExtra(PayResultActivity.KEY_ORDER_ID, re.getData().getOrderid());
					successIntent.putExtra(PayResultActivity.KEY_PAY_TIME, re.getData().getPaytime());
					startActivity(successIntent);
					finish();
				} else {
//					showToast(resultData.getMsg());
					Intent failureIntent = new Intent(PayActivity.this, PayResultActivity.class);
					failureIntent.putExtra(PayResultActivity.KEY_RESULT, PayResultActivity.VALUE_FAILURE);
					failureIntent.putExtra(PayResultActivity.KEY_FAILURE_REASON, resultData.getMsg());
					startActivity(failureIntent);
					finish();
				}
			}
			
			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(R.string.please_check_network);
			}
		});
	}
	
//	private void toOrderDetail() {
//		Intent intent = new Intent(PayActivity.this,OrderDetailShipperActivity.class);
//		intent.putExtra(ExtraName.orderid, orderid);
//		startActivity(intent);
//	}
	
	  //-----------------------------aliPay-------------------------------------------

	
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;

    public void aliPay() {
        String orderInfo = getOrderInfo("田贸e通", "田贸e通 "+aliPayResult.getData().getMoney()+"元", aliPayResult.getData().getMoney());
        String sign = sign(orderInfo);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                + getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(PayActivity.this);
                // 调用支付接口
				String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * create the order info. 创建订单信息
     *
     */
    public String getOrderInfo(String subject, String body, String price) {
        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + Constants.PARTNER + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + Constants.SELLER + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + subject + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + body + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + price + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + aliPayResult.getData().getAlipay().getNotifyurl() +"\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;

    }

    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content
     *            待签名订单信息
     */
    public String sign(String content) {
        return SignUtils.sign(content, Constants.RSA_PRIVATE);
    }

    /**
     * get the sign type we use. 获取签名方式
     *
     */
    public String getSignType() {
        return "sign_type=\"RSA\"";
    }

    public String getOutTradeNo() {

        return aliPayResult.getData().getPayorderid();
    }

    /**
     * check whether the device has authentication alipay account.
     * 查询终端设备是否存在支付宝认证账户
     *
     */
    public void check(View v) {
        Runnable checkRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask payTask = new PayTask(PayActivity.this);
//                boolean isExist = payTask.checkAccountIfExist();

                Message msg = new Message();
                msg.what = SDK_CHECK_FLAG;
//                msg.obj = isExist;
                mHandler.sendMessage(msg);
            }
        };

        Thread checkThread = new Thread(checkRunnable);
        checkThread.start();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case SDK_PAY_FLAG: {
                PayResult resultObj = new PayResult((String) msg.obj);
                String resultStatus = resultObj.getResultStatus();

                // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                if (TextUtils.equals(resultStatus, "9000")) {
					// ToastUtil. toast("支付成功");
					PayResult.ResultModel rm = PayResult.parseResult(resultObj.getResult());
					Intent successIntent = new Intent(PayActivity.this, PayResultActivity.class);
					successIntent.putExtra(PayResultActivity.FORWARD_KEY, PayResultActivity.FORWARD_CART_ORDER_LIST);
					successIntent.putExtra(PayResultActivity.KEY_RESULT, PayResultActivity.VALUE_SUCCESS);
					successIntent.putExtra(PayResultActivity.KEY_MONEY, aliPayResult.getData().getMoney() + "元");
					successIntent.putExtra(PayResultActivity.KEY_PAY_WAY, "支付宝");
					successIntent.putExtra(PayResultActivity.KEY_ORDER_ID, aliPayResult.getData().getOrderid());
					successIntent.putExtra(PayResultActivity.KEY_PAY_TIME, aliPayResult.getData().getPaytime());
					startActivity(successIntent);
					finish();
				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”
					// 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					String result = null;
					if (TextUtils.equals(resultStatus, "8000")) {
						result = "支付结果确认中";
					} else {
						result = "支付失败";
					}
					Intent successIntent = new Intent(PayActivity.this, PayResultActivity.class);
					successIntent.putExtra(PayResultActivity.KEY_RESULT, PayResultActivity.VALUE_FAILURE);
					successIntent.putExtra(PayResultActivity.KEY_FAILURE_REASON, result);
					startActivity(successIntent);
					finish();
				}
                break;
            }
            case SDK_CHECK_FLAG: {
                ToastUtil. toast("检查结果为：" + msg.obj);
                break;
            }
            default:
                break;
            }
        };
    };
    
    
    //---------------------wx
    
    PayReq req;
    final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
//  TextView show;
//  Map<String,String> resultunifiedorder;
    StringBuffer sb;
    
    private void initWx(){
        req = new PayReq();
        sb=new StringBuffer();
        msgApi.registerApp(Constants.APP_ID);
    }
    
    private void genPayReq() {

        req.appId = Constants.APP_ID;
        req.partnerId = Constants.MCH_ID;
//      req.prepayId = resultunifiedorder.get("prepay_id");
//      req.packageValue = "prepay_id="+resultunifiedorder.get("prepay_id");
        req.prepayId = weixinResult.getData().getWeixin().getPrepayid();
        req.packageValue = "prepay_id="+weixinResult.getData().getWeixin().getPrepayid();
        req.nonceStr = genNonceStr();
        req.timeStamp = String.valueOf(genTimeStamp());


        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

        req.sign = genAppSign(signParams);

        sb.append("sign\n"+req.sign+"\n\n");

//      show.setText(sb.toString());

        Log.e("orion", signParams.toString());

    }
    private String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }
    
    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }
    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(Constants.API_KEY);

        this.sb.append("sign str\n"+sb.toString()+"\n\n");
        String appSign = MD5.getMessageDigest(sb.toString().getBytes());
        Log.e("orion",appSign);
        return appSign;
    }
    
    private void sendPayReq() {
        msgApi.registerApp(Constants.APP_ID);
        msgApi.sendReq(req);
    }

    @Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		msgApi.handleIntent(intent, this);
	}

	@Override
	public void onReq(BaseReq req) {
	}

	@Override
	public void onResp(BaseResp resp) {
		if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
			if(resp.errCode == 0){
				showToast("支付成功");
			}else if(resp.errCode == -1){
				showToast("支付错误");
			}else if(resp.errCode == -2){
				showToast("支付取消");
			}
		}
	}
}
